package com.yuhong.reggie.service.impl;

import com.yuhong.reggie.entity.ShoppingCart;
import com.yuhong.reggie.mapper.ShoppingCartMapper;
import com.yuhong.reggie.service.ShoppingCartSerivce;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class ShoppingCartSerivceImpl implements ShoppingCartSerivce {

    @Autowired(required = false)
    private ShoppingCartMapper shoppingCartMapper;
    /**
     * 添加购物车
     *
     * @param shoppingCart
     * @return ShoppingCart
     */
    @Override
    public ShoppingCart addCart(ShoppingCart shoppingCart) {
        //获取mappre的数据
        ShoppingCart dbShopping = shoppingCartMapper.findByShoppingCart(shoppingCart);
        //判断当前加入的菜品或套餐在当前购物车有误数据
        if (dbShopping!=null){
            //如果有,数量加一
            dbShopping.setNumber(dbShopping.getNumber()+1);
            //调用mapper修改方法把当前获得的数量加入进去
            shoppingCartMapper.updateNumber(dbShopping.getId(),dbShopping.getNumber());
        }else {
            //如果没有,插入一条新的数据
            dbShopping=shoppingCart;
            dbShopping.setCreateTime(LocalDateTime.now());
            dbShopping.setNumber(1);
            shoppingCartMapper.save(dbShopping);
        }
        return dbShopping;
    }

    /**
     * 减少购物车
     *
     * @param shoppingCart
     * @return
     */
    @Override
    public ShoppingCart subCart(ShoppingCart shoppingCart) {
        ShoppingCart dbShopping = shoppingCartMapper.findByShoppingCart(shoppingCart);
        //判断当前加入的菜品或套餐在当前购物车有误数据
        if (dbShopping!=null){
            //有数据
            if (dbShopping.getNumber()>0){
                dbShopping.setNumber(dbShopping.getNumber()-1);
                shoppingCartMapper.updateNumber(dbShopping.getId(),dbShopping.getNumber());

            }else {
                return null;
            }
        }

        return dbShopping;
    }

    /**
     * 查询购物车
     *
     * @param userId
     * @return
     */
    @Override
    public List<ShoppingCart> findShopping(Long userId) {

        return shoppingCartMapper.findAllByUserId(userId);
    }

    /**
     * 删除购物车
     *
     * @param id
     * @return
     */
    @Override
    public Integer delete(Long id) {
        return shoppingCartMapper.delete(id);
    }
}
